package eu.trojanbug.spring.security.gae;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.AuthenticationEntryPoint;
import org.springframework.security.ui.ExceptionTranslationFilter;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Used by the {@link ExceptionTranslationFilter} to commence a Google form login
 * and later authenticate via the {@link GAEAuthenticationProcessingFilter}. 
 * This object determines the login form URL basing on own request URL, 
 * as described in GAE Google Accounts Service documentation.
 * 
 * @author Krzysztof Trojan
 */
public class GoogleLoginAuthenticationEntryPoint implements
		AuthenticationEntryPoint {

	private static final Log logger = LogFactory
			.getLog(GoogleLoginAuthenticationEntryPoint.class);

	/**
	 * Performs the redirect to the login form URL.
	 */
	public void commence(ServletRequest request, ServletResponse response,
			AuthenticationException authException) throws IOException,
			ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		UserService userService = UserServiceFactory.getUserService();

		String thisURL = httpRequest.getRequestURI();
		thisURL = httpResponse.encodeRedirectURL(thisURL);
		String loginPageRedirectURL = userService.createLoginURL(thisURL);
		
		if (logger.isDebugEnabled())
		  logger.debug("Google Accounts login triggered by calling to GoogleLoginAuthenticationEntryPoint. Sending redirect to login page at "+loginPageRedirectURL);
		
		httpResponse.sendRedirect(loginPageRedirectURL);
	}

}
